import React, { useState, useRef, useEffect } from 'react'
import { useDispatch } from 'react-redux'
import classNames from 'classnames'
import { delTodo } from '../../store/actions'
import { changeStatus } from '../../store/actions/todo'
export default function TodoItem({ item }) {
  const dispatch = useDispatch()
  const inputRef = useRef()
  const [currentId, setCurrentId] = useState('')
  const handleDel = (id) => dispatch(delTodo(id))
  const handleChangeStatus = (id) => dispatch(changeStatus(id))
  const handleDBLLable = (id) => setCurrentId(id)
  useEffect(() => inputRef.current.focus(), [currentId])
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: item.id === currentId,
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleChangeStatus(item.id)}
        />
        <label onDoubleClick={() => handleDBLLable(item.id)}>{item.name}</label>
        <button className='destroy' onClick={() => handleDel(item.id)}></button>
      </div>
      {/* #2. ref 引用和 input 编辑框进行绑定 */}
      <input
        className='edit'
        value='Create a TodoMVC template'
        onChange={() => {}}
        ref={inputRef}
      />
    </li>
  )
}
